<template>
  <div v-drag v-show="isChartShow" id="chart-main">
    <transition name="el-zoom-in-top">
      <div v-show="isChartShow" id="chart" class="div-chartMain">
        <div class="char-header">
          <span>{{ currentSearchLayer ? currentSearchLayer.name :'' }} </span>
          <i
            type="text"
            class="chartModulePanelClose el-icon-close"
            style="float: right;"
            @click="close($event)"
          />
        </div>
        <div v-loading="loading" class="char-content">
          <div class="chart-content-option">
            <el-row>
              <el-col :span="18">
                <div class="chart-content-option-bg0">
                  <el-select v-model="selectField" placeholder="请选择统计类型" size="small" @change="queryStatics">
                    <el-option
                      v-for="item in options"
                      :key="item"
                      :label="item"
                      :value="item"/>
                  </el-select>
                </div>
              </el-col>
              <el-col :span="2">
                <div class="chart-content-option-bg1">
                  <el-tooltip class="item" effect="dark" content="柱状图" placement="bottom">
                    <el-button icon="kfb-icon-zhuzhuangtu" @click="staticsMap(0)"/>
                  </el-tooltip>
                </div>
              </el-col>
              <el-col :span="2">
                <div class="chart-content-option-bg1">
                  <el-tooltip class="item" effect="dark" content="饼状图" placement="bottom">
                    <el-button icon="kfb-icon-bingzhuangtu1" @click="staticsMap(1)"/>
                  </el-tooltip>
                </div>
              </el-col>
              <el-col :span="2">
                <div class="chart-content-option-bg1">
                  <el-tooltip class="item" effect="dark" content="折线图" placement="bottom">
                    <el-button icon="kfb-icon-zhexiantu" @click="staticsMap(2)"/>
                  </el-tooltip>
                </div>
              </el-col>
            </el-row>
          </div>
          <div class="chart-content-cantiner">
            <e-charts ref="echart" :options="barOption" autoresize/>
          </div>
        </div>
      </div>
    </transition>
  </div>

</template>
<script>

  // 引入v-echars
  import ECharts from 'vue-echarts'
  import theme from '@/assets/echartTheme/shine.project.json'

  ECharts.registerTheme('shine', theme) // 引入主题
  import { mapState } from 'vuex'

  // 手动引入Echarts
  import 'echarts/lib/chart/bar'
  import 'echarts/lib/chart/pie'
  import 'echarts/lib/chart/line'
  import 'echarts/lib/component/tooltip'
  import 'echarts/lib/component/polar'
  import 'echarts/lib/component/legend'
  import 'echarts/lib/component/title.js'
  import 'echarts/lib/component/markPoint.js'
  import 'echarts/lib/component/markLine.js'
  import 'echarts/lib/chart/gauge'

  export default {
    name: 'Chart',
    components: { ECharts },
    directives: {
      drag: {
        // 指令的定义
        bind: function(el) {
          const odiv = el // 获取当前元素
          odiv.onmousedown = e => {
            // 算出鼠标相对元素的位置
            const disX = e.clientX - odiv.offsetLeft
            const disY = e.clientY - odiv.offsetTop
            //console.log(disX);
            document.onmousemove = e => {
              // 用鼠标的位置减去鼠标相对元素的位置，得到元素的位置
              const left = e.clientX - disX
              const top = e.clientY - disY
              // 移动当前元素
              odiv.style.left = left + 'px'
              odiv.style.top = top + 'px'
            }
            document.onmouseup = e => {
              document.onmousemove = null
              document.onmouseup = null
            }
          }
        }
      }
    },
    data() {
      return {
        staticsType: '',
        loading: false, // 加载等待框
        layerName: '',
        // 柱状图
        barOption: {},
        // 饼状图
        pieOption: {},
        // 折线图
        lineOption: {},
        selectField: undefined
      }
    },
    methods: {

      close(env) {
        this.$store.commit('eswyzt/setShowLayerStatics', false)
      },

      /**
       *  切换统计图表类型
       */
      staticsMap(type) {
        switch (type) {
          case 0:
            this.$refs.echart.options = this.barOption
            break
          case 1:
            this.$refs.echart.options = this.pieOption
            break
          case 2:
            this.$refs.echart.options = this.lineOption
            break
        }
      },

      /**
       * 统计数据
       */
      queryStatics() {
        this.loading = true
        const url = this.currentSearchLayer.statics.url
        const layername = this.currentSearchLayer.statics.layer
        const field = this.selectField
        const statics = this.currentSearchLayer.statics.mode
        return new Promise((resolve, reject) => {
          this.mapService.queryLayerStatics(url, layername, field).then(res => {
            const features = res.result.recordsets[0].features.features
            const data = []
            const value = []
            const datapiefommat = []
            features.forEach((fea) => {
              data.push(fea.properties[field])
              value.push(fea.properties[statics])
              datapiefommat.push({ value: fea.properties[statics], name: fea.properties[field] })
            })
            this.barOption = this.buildBarStatics(this.currentSearchLayer.name, data, value)
            this.pieOption = this.buildPieStatics(this.currentSearchLayer.name, datapiefommat)
            this.lineOption = this.buildLineStatics(this.currentSearchLayer.name, data, value)
            this.loading = false
          }).catch(e => {
            this.loading = false
          })
        })
      },

      /**
       * 构建柱状图
       */
      buildBarStatics(title, data, value) {
        return {
          title: {
            text: title,
            x: 'center'
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              // 坐标轴指示器，坐标轴触发有效
              type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          yAxis: {
            type: 'value'
          },
          xAxis: {
            type: 'category',
            data: data
          },
          series: [
            {
              name: '数量',
              type: 'bar',
              stack: '数量',
              label: {
                normal: {
                  show: true
                }
              },
              data: value
            }
          ]
        }
      },
      /**
       * 构建饼状图
       */
      buildPieStatics(title, data) {
        return {
          title: {
            text: title,
            x: 'center'
          },
          tooltip: {
            trigger: 'item',
            formatter: '{a} <br/>{b} : {c} ({d}%)'
          },
          toolbox: {
            show: true,
            feature: {
              mark: { show: true },
              dataView: { show: true, readOnly: false },
              magicType: {
                show: true,
                type: ['pie', 'funnel']
              },
              restore: { show: true },
              saveAsImage: { show: true }
            }
          },
          calculable: true,
          series: [
            {
              name: '数量',
              type: 'pie',
              radius: '55%',
              center: ['50%', '50%'],
              data: data,
              itemStyle: {
                emphasis: {
                  shadowBlur: 10,
                  shadowOffsetX: 0,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }
          ]
        }
      },
      /**
       * 构建折线图
       */
      buildLineStatics(title, data, value) {
        return {
          title: {
            text: title,
            x: 'center'
          },
          tooltip: {
            trigger: 'axis',
            axisPointer: {
              // 坐标轴指示器，坐标轴触发有效
              type: 'shadow' // 默认为直线，可选为：'line' | 'shadow'
            }
          },
          grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
          },
          yAxis: {
            type: 'value'
          },
          xAxis: {
            type: 'category',
            data: data
          },
          series: [
            {
              name: '数量',
              type: 'line',
              stack: '数量',
              label: {
                normal: {
                  show: true
                }
              },
              data: value
            }
          ]
        }
      }
    },
    computed: {
      ...mapState({
        options(state) {
          const d = state.eswyzt.currentSearchLayer
          if (d && d.statics.fields.split(',').length > 0) {
            this.selectField = d.statics.fields.split(',')[0]
          }
          return d ? d.statics.fields.split(',') : []
        },
        /**
         * 当前查询自定义图层
         * @param state
         * @returns {currentSearchLayer|(function(*))|*}
         */
        currentSearchLayer(state) {
          return state.eswyzt.currentSearchLayer
        },
        /**
         * 显示统计查询数据组件
         * @param state
         * @returns {*}
         */
        isChartShow(state) {
          return state.eswyzt.showLayerStatics
        },

        mapService(state) {
          return state.eswyzt.mapService;
        },
         mapServiceSync(state) {
          return state.eswyzt.mapServiceSync;
        }
      })
    },
    watch: {
      options: function(n, o) {
        this.queryStatics()
      }
    },
    mounted() {
    }

  }
</script>

<style scoped>
  #chart-main{
    position: absolute;
    bottom: 10px;
    right: 20px;
    width: 500px;
    height: 435px;
    z-index: 999;
    background-color: #0000;
  }
  .div-chartMain {
    width: 100%;
    height: 100%;
    background-color: #0000;
    font-family: "microsoft yahei", arial, tahoma, helvetica, sans-serif;
  }

  .char-header {
    color: #409eff;
    padding: 6px 15px;
    padding-right: 4px;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
    font-size: 15px;
    background-color: #398f8699;
    margin-bottom: 0px;
    height: 35px;
  }

  .chartModulePanelClose {
    position: absolute;
    right: -19px;
    margin: 10px;
    top: -20px;
    font-size: 16px;
    transition: transform 0.3s;
    background-color: #f44336;
    border-radius: 10px;
    color: #fff;
    padding: 2px;
    z-index: 900;
    cursor: pointer;
  }

  .char-content {
    height: 400px;
    background-color: #0005;
  }

  .chart-content-option {

  }

  .chart-content-option-bg0 {
    height: 40px;
    line-height: 40px;
    text-align: left;
    margin-left: 10px;
  }

  .chart-content-option-bg1 {
    height: 40px;
    line-height: 40px;
    text-align: center;
  }

  .chart-content-cantiner {
    height: calc(100% - 40px);
  }

  .echarts {
    width: 100%;
    height: 100%;
  }

  .el-button {
    width: 32px;
    height: 32px;
    padding: 6px !important;
    background-color: transparent;
    border-color: transparent;
    outline: none;
  }
</style>
